//
//  ViewController.swift
//  Combine-IAP-Demo
//
//  Created by garvin on 2025/7/3.
//

import UIKit
import StoreKit
import Combine

class ViewController: UIViewController {
    
    // MARK: - UI 控件
    @IBOutlet weak var productInfoLabel: UILabel!
    @IBOutlet weak var statusLabel: UILabel!
    @IBOutlet weak var loadProductButton: UIButton!
    @IBOutlet weak var purchaseButton: UIButton!
    @IBOutlet weak var restoreButton: UIButton!
    @IBOutlet weak var productIDTextField: UITextField!
    
    // MARK: - 属性
    private let iapManager = CombineIAPManager.shared
    private var cancellables = Set<AnyCancellable>()
    private var currentProduct: SKProduct?
    
    // 示例商品ID（实际使用时应该从后台获取）
    private let sampleProductID = "com.example.premium"

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupBindings()
        CurrentValueSubject
        "".publisher
            .era
        print("=======")
        print("🛒 Combine IAP Demo 启动")
        print("🛒 可以进行购买: \(iapManager.canMakePayments())")
    }
    
    // MARK: - UI 设置
    private func setupUI() {
        title = "Combine IAP Demo"
        view.backgroundColor = .systemBackground
        
        setupUIControls()
        setupConstraints()
        
        // 设置默认商品ID
        productIDTextField.text = sampleProductID
        productIDTextField.placeholder = "请输入商品ID"
        
        // 设置初始状态
        updateUI(for: .idle)
        
        // 按钮样式
        styleButton(loadProductButton, title: "获取商品信息", color: .systemBlue)
        styleButton(purchaseButton, title: "购买", color: .systemGreen)
        styleButton(restoreButton, title: "恢复购买", color: .systemOrange)
        
        // 初始状态
        purchaseButton.isEnabled = false
        
        // 标签样式
        productInfoLabel.numberOfLines = 0
        productInfoLabel.textAlignment = .center
        statusLabel.numberOfLines = 0
        statusLabel.textAlignment = .center
        statusLabel.textColor = .systemGray
    }
    
    private func setupUIControls() {
        // 创建UI控件
        productIDTextField = UITextField()
        productInfoLabel = UILabel()
        statusLabel = UILabel()
        loadProductButton = UIButton(type: .system)
        purchaseButton = UIButton(type: .system)
        restoreButton = UIButton(type: .system)
        
        // 设置边框
        productIDTextField.borderStyle = .roundedRect
        productIDTextField.textAlignment = .center
        
        // 添加到视图
        [productIDTextField, productInfoLabel, statusLabel, loadProductButton, purchaseButton, restoreButton].forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview($0)
        }
    }
    
    private func setupConstraints() {
        NSLayoutConstraint.activate([
            // 商品ID输入框
            productIDTextField.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            productIDTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            productIDTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            productIDTextField.heightAnchor.constraint(equalToConstant: 44),
            
            // 获取商品信息按钮
            loadProductButton.topAnchor.constraint(equalTo: productIDTextField.bottomAnchor, constant: 20),
            loadProductButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            loadProductButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            loadProductButton.heightAnchor.constraint(equalToConstant: 44),
            
            // 商品信息标签
            productInfoLabel.topAnchor.constraint(equalTo: loadProductButton.bottomAnchor, constant: 30),
            productInfoLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            productInfoLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            
            // 购买按钮
            purchaseButton.topAnchor.constraint(equalTo: productInfoLabel.bottomAnchor, constant: 30),
            purchaseButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            purchaseButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            purchaseButton.heightAnchor.constraint(equalToConstant: 44),
            
            // 恢复购买按钮
            restoreButton.topAnchor.constraint(equalTo: purchaseButton.bottomAnchor, constant: 20),
            restoreButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            restoreButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            restoreButton.heightAnchor.constraint(equalToConstant: 44),
            
            // 状态标签
            statusLabel.topAnchor.constraint(equalTo: restoreButton.bottomAnchor, constant: 30),
            statusLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            statusLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
        ])
    }
    
    private func styleButton(_ button: UIButton, title: String, color: UIColor) {
        button.setTitle(title, for: .normal)
        button.backgroundColor = color
        button.setTitleColor(.white, for: .normal)
        button.layer.cornerRadius = 8
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        
        // 添加事件
        switch button {
        case loadProductButton:
            button.addTarget(self, action: #selector(loadProductTapped), for: .touchUpInside)
        case purchaseButton:
            button.addTarget(self, action: #selector(purchaseTapped), for: .touchUpInside)
        case restoreButton:
            button.addTarget(self, action: #selector(restoreTapped), for: .touchUpInside)
        default:
            break
        }
    }
    
    // MARK: - Combine 绑定
    private func setupBindings() {
        // 监听购买状态更新
        iapManager.purchaseStateUpdates
            .receive(on: DispatchQueue.main)
            .sink { [weak self] state in
                self?.handlePurchaseState(state)
            }
            .store(in: &cancellables)
        
        // 监听交易更新（用于调试）
        iapManager.transactionUpdates
            .receive(on: DispatchQueue.main)
            .sink { [weak self] transaction in
                print("🛒 交易更新: \(transaction.payment.productIdentifier) - 状态: \(transaction.transactionState.rawValue)")
            }
            .store(in: &cancellables)
    }
    
    // MARK: - 按钮事件
    @objc private func loadProductTapped() {
        guard let productID = productIDTextField.text, !productID.isEmpty else {
            showAlert(title: "错误", message: "请输入有效的商品ID")
            return
        }
        
        updateUI(for: .loading)
        
        iapManager.loadProduct(productID: productID)
            .receive(on: DispatchQueue.main)
            .sink(
                receiveCompletion: { [weak self] completion in
                    if case .failure(let error) = completion {
                        self?.showAlert(title: "获取商品失败", message: error.localizedDescription)
                        self?.updateUI(for: .idle)
                    }
                },
                receiveValue: { [weak self] product in
                    self?.currentProduct = product
                    self?.updateUI(for: .productLoaded(product))
                    print("🛒 产品加载成功: \(product.displayInfo)")
                }
            )
            .store(in: &cancellables)
    }
    
    @objc private func purchaseTapped() {
        guard let product = currentProduct else {
            showAlert(title: "错误", message: "请先获取商品信息")
            return
        }
        
        updateUI(for: .purchasing)
        
        iapManager.purchase(product)
            .receive(on: DispatchQueue.main)
            .sink(
                receiveCompletion: { [weak self] completion in
                    if case .failure(let error) = completion {
                        self?.showAlert(title: "购买失败", message: error.localizedDescription)
                        if let product = self?.currentProduct {
                            self?.updateUI(for: .productLoaded(product))
                        }
                    }
                },
                receiveValue: { [weak self] state in
                    self?.handlePurchaseState(state)
                }
            )
            .store(in: &cancellables)
    }
    
    @objc private func restoreTapped() {
        updateUI(for: .restoring)
        
        iapManager.restorePurchases()
            .receive(on: DispatchQueue.main)
            .sink(
                receiveCompletion: { [weak self] completion in
                    if case .failure(let error) = completion {
                        self?.showAlert(title: "恢复失败", message: error.localizedDescription)
                    }
                    self?.updateUI(for: .idle)
                },
                receiveValue: { [weak self] transactions in
                    let message = transactions.isEmpty ? "没有可恢复的购买" : "成功恢复 \(transactions.count) 个购买"
                    self?.showAlert(title: "恢复完成", message: message)
                }
            )
            .store(in: &cancellables)
    }
    
    // MARK: - 状态处理
    private func handlePurchaseState(_ state: PurchaseState) {
        switch state {
        case .purchasing:
            updateUI(for: .purchasing)
        case .purchased(let transaction):
            showAlert(title: "购买成功", message: "商品购买成功！\n交易ID: \(transaction.transactionIdentifier ?? "无")")
            updateUI(for: .purchased)
        case .failed(let error):
            showAlert(title: "购买失败", message: error.localizedDescription)
            if let product = currentProduct {
                updateUI(for: .productLoaded(product))
            }
        case .deferred:
            showAlert(title: "购买延期", message: "购买需要等待批准（如家庭共享）")
        }
    }
    
    // MARK: - UI 状态管理
    enum UIState {
        case idle
        case loading
        case productLoaded(SKProduct)
        case purchasing
        case restoring
        case purchased
    }
    
    private func updateUI(for state: UIState) {
        switch state {
        case .idle:
            productInfoLabel.text = "请输入商品ID并获取商品信息"
            statusLabel.text = "就绪"
            loadProductButton.isEnabled = true
            purchaseButton.isEnabled = false
            restoreButton.isEnabled = true
            productIDTextField.isEnabled = true
            
        case .loading:
            productInfoLabel.text = "正在获取商品信息..."
            statusLabel.text = "加载中"
            loadProductButton.isEnabled = false
            purchaseButton.isEnabled = false
            restoreButton.isEnabled = false
            
        case .productLoaded(let product):
            productInfoLabel.text = product.detailedInfo
            statusLabel.text = "商品信息已加载"
            loadProductButton.isEnabled = true
            purchaseButton.isEnabled = true
            restoreButton.isEnabled = true
            
        case .purchasing:
            statusLabel.text = "正在购买..."
            loadProductButton.isEnabled = false
            purchaseButton.isEnabled = false
            restoreButton.isEnabled = false
            
        case .restoring:
            statusLabel.text = "正在恢复购买..."
            loadProductButton.isEnabled = false
            purchaseButton.isEnabled = false
            restoreButton.isEnabled = false
            
        case .purchased:
            statusLabel.text = "购买成功！"
            loadProductButton.isEnabled = true
            purchaseButton.isEnabled = false
            restoreButton.isEnabled = true
        }
    }
    
    // MARK: - 辅助方法
    private func showAlert(title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}

